package com.mantru.iotpot.dishes

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.EditText
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.distinctUntilChanged
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.mantru.iotpot.Adapter.DishesCreateAdapter
import com.mantru.iotpot.ApplicationClass
import com.mantru.iotpot.Cook.CookActivity
import com.mantru.iotpot.Dialog.AddStepDialog
import com.mantru.iotpot.R
import com.mantru.iotpot.Tools.LoadingDialogUtil
import com.mantru.iotpot.Util.InternalFileSaver
import com.mantru.iotpot.Util.TimeUtil
import com.mantru.iotpot.Util.ToastUtils
import com.mantru.iotpot.databinding.ActivityDishesCreateBinding
import com.squareup.picasso.Picasso
import org.json.JSONArray
import org.json.JSONObject

class DishesCreateActivity : AppCompatActivity() {
    val viewModel by viewModels<DishesCreateViewModel>()
    private lateinit var binding: ActivityDishesCreateBinding
    //adapter属于UI层，负责交互，留在Activity
    private var dishesCreateAdapter: DishesCreateAdapter? = null
    //监听recyclerview滑动方向
    var moveY: Int = 0
    var lastFirstItem = 0
    var lastLastItem = 0
    //插入步骤弹窗
    private var addStepDialog: AddStepDialog? = null
    var currentSelectedIndex: Int = 0 // 当前选中的 index
    //保存上一次的酱料名称列表和食材名称列表,用于删除
    var oldSauceList: MutableList<String> = mutableListOf()
    //在这里接收食材搜索页面的结果
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if ( resultCode == RESULT_OK ){
            when ( requestCode ){
                1001 ->{//食材选择
                    data?.let {
                        val position = it.getIntExtra("position", -1)
                        val parentPosition = it.getIntExtra("parentPosition", -1)
                        val foodNameList = it.getStringArrayListExtra("foodName") ?: arrayListOf()

                        // 获取当前的box_name_List_List
                        val boxNameListList = viewModel.box_name_List_List.get() ?: mutableListOf()

                        // 处理foodNameList：去重并转换为逗号分隔字符串
                        val processedFoodName = if (foodNameList.isNotEmpty()) {
                            foodNameList.toSet().joinToString("、") // 去重并拼接
                        } else {
                            "" // 如果列表为空，设置为空字符串
                        }
                        // 确保位置有效
                        if (parentPosition >= 0 && parentPosition < boxNameListList.size) {
                            val innerList = boxNameListList[parentPosition]
                            if (position >= 0 && position < innerList.size) {
                                // 替换指定位置的值
                                innerList[position] = processedFoodName
                                boxNameListList[parentPosition] = innerList
                            } else if (position >= 0) {
                                // 如果位置超出当前列表范围，扩展列表
                                while (innerList.size <= position) {
                                    innerList.add("")
                                }
                                innerList[position] = processedFoodName
                                boxNameListList[parentPosition] = innerList
                            }
                        } else if (parentPosition >= 0) {
                            // 如果外层位置超出范围，扩展外层列表
                            while (boxNameListList.size <= parentPosition) {
                                boxNameListList.add(mutableListOf(""))
                            }
                            val newInnerList = mutableListOf<String>()
                            if (position >= 0) {
                                while (newInnerList.size <= position) {
                                    newInnerList.add("")
                                }
                                newInnerList[position] = processedFoodName
                            }
                            boxNameListList[parentPosition] = newInnerList
                        }

                        // 更新到viewModel
                        viewModel.box_name_List_List.set(boxNameListList)
                        dishesCreateAdapter?.notifyItemRangeChanged(parentPosition, 1)
                    }
                }
                2001 ->{//菜谱照片选择
                    data?.let {
                        viewModel.vegetableImageUrl = it.getStringExtra("vegetableImage").toString()
                        //同时把菜谱图片保存本地,但需要http开头的网络图片才保存
                        if ( viewModel.vegetableImageUrl.startsWith("http") ){
                            InternalFileSaver.saveToPrivateFile(this@DishesCreateActivity, viewModel.vegetableImageUrl, viewModel.vegetableImageUrl.replace("http://iotapi.mantru.com/upload/share_image/","")) {
                            }
                        }
                        //设置图片
                        Picasso.get().load(viewModel.vegetableImageUrl).into(binding.dishesCreateDetailImage)
                    }
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_dishes_create)
        binding.viewModel = viewModel // 绑定viewModel
        binding.lifecycleOwner = this // 允许 LiveData 自动更新 UI

        //初始化recyclerview
        setRecyclerView()
        //设置控件交互事件
        setContentAction()
        //观察者模式，观察dishesList变化，更新adapter数据
        setupObservers()
        setupHttpResultObservers()

        // 初始化 numList和weightList以及name
        //获取获取可能的vegetableId
        val vegetableId = intent.getIntExtra("vegetableId", -1)
        Log.d("DishesCreateActivity", "vegetableId: $vegetableId")
        //大于0说明是从其他页面进来的，不进行初始化，直接赋值
        if ( vegetableId >= 0 ){
            //赋值vegetableId用于保存
            viewModel.vegetableId.set(vegetableId)
            //获取菜谱详情数据
            val map: MutableMap<String, Any> = HashMap()
            map["vegetable_id"] = vegetableId
            viewModel.getHttpValue("GetSQLData_Vegetable_Entity_For_Edit", map, "")
        } else {
            val numList = intent.getStringArrayListExtra("numList")
            numList?.let {
                viewModel.numberList.set(it.toMutableList())
                binding.dishesCreateDetailNum.text = viewModel.numberList.get()!![0]
            }
            val weightList = intent.getStringArrayListExtra("weightList")
            weightList?.let {
                viewModel.weightList.set(it.toMutableList())
                binding.dishesCreateDetailWeight.text = viewModel.weightList.get()!![0] + "g"
            }
            val name = intent.getStringExtra("name")
            name?.let {
                viewModel.name.set(it)
            }

            // 默认加载第一个 index 的数据
            if (!numList.isNullOrEmpty()) {
                currentSelectedIndex = 0
                viewModel.loadDateForIndex(currentSelectedIndex)
            }
        }
    }

    override fun onStop() {
        super.onStop()
        //如果有Loading弹窗，关闭弹窗
        LoadingDialogUtil.closeLoadingDialog()
    }

    //初始化recyclerview
    private fun setRecyclerView(){
        dishesCreateAdapter = DishesCreateAdapter(this, R.layout.adapter_dishes_create, viewModel.dishesCreateList.value ?: mutableListOf())
        binding.dishesCreateRecyclerview.apply {
            setLayoutManager(StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL))
            adapter = dishesCreateAdapter
        }
    }

    //设置控件交互事件
    @SuppressLint("NotifyDataSetChanged")
    private fun setContentAction(){
        //关闭按钮
        binding.dishesCreateBack.setOnClickListener {
            finish()
        }

        //选择规格按钮
        binding.dishesCreateSpecs.setOnClickListener {
            //判断当前是否可以更换规格
            if ( !viewModel.judgeAddItem("选择规格") ){
                return@setOnClickListener
            }
            // 切换规格前保存当前规格的数据
            viewModel.saveCurrentSpecData(currentSelectedIndex)
            //弹出选择弹窗,并赋值给currentSelectedIndex
            showSpecDialog()
        }

        //点击菜谱图片
        binding.dishesCreateDetailImageLayout.setOnClickListener {
            val intent = Intent(this@DishesCreateActivity, DishesCreateImageActivity::class.java)
            startActivityForResult(intent, 2001)
        }

        //时序图按钮
        binding.dishesCreateTimePage.setOnClickListener {
            //判断当前是否可以点击时序图
            if ( !viewModel.judgeAddItem("时序图") ){
                return@setOnClickListener
            }
            // 切换规格前保存当前规格的数据
            viewModel.saveCurrentSpecData(currentSelectedIndex)

            //先转成String然后带到时序图页面
            val currentSpecData = viewModel.dataMap[currentSelectedIndex]
            if ( currentSpecData != null ){
                val specDataJson = JSONObject().apply {
                    put("steep_type_Lists", JSONArray(currentSpecData.steep_type_Lists.toList().toMutableList()))
                    put("steep_index_Lists", JSONArray(currentSpecData.steep_index_Lists.toList().toMutableList()))
                    put("fire_value_Lists", JSONArray(currentSpecData.fire_value_Lists.toList().toMutableList()))
                    put("time_value_Lists", JSONArray(currentSpecData.time_value_Lists.toList().toMutableList()))
                    put("time_long_Lists", JSONArray(currentSpecData.time_long_Lists.toList().toMutableList()))
                    put("gripper_speed_value_Lists", JSONArray(currentSpecData.gripper_speed_value_Lists.toList().toMutableList()))
                    put("gripper_rotation_value_Lists", JSONArray(currentSpecData.gripper_rotation_value_Lists.toList().toMutableList()))
                    put("gripper_position_value_Lists", JSONArray(currentSpecData.gripper_position_value_Lists.toList().toMutableList()))
                    put("nozzle1_value_Lists", JSONArray(currentSpecData.nozzle1_value_Lists.toList().toMutableList()))
                    put("nozzle2_value_Lists", JSONArray(currentSpecData.nozzle2_value_Lists.toList().toMutableList()))
                    put("nozzle3_value_Lists", JSONArray(currentSpecData.nozzle3_value_Lists.toList().toMutableList()))
                    put("nozzle4_value_Lists", JSONArray(currentSpecData.nozzle4_value_Lists.toList().toMutableList()))
                    put("nozzle5_value_Lists", JSONArray(currentSpecData.nozzle5_value_Lists.toList().toMutableList()))
                    put("nozzle6_value_Lists", JSONArray(currentSpecData.nozzle6_value_Lists.toList().toMutableList()))
                    put("nozzle7_value_Lists", JSONArray(currentSpecData.nozzle7_value_Lists.toList().toMutableList()))
                    put("nozzle8_value_Lists", JSONArray(currentSpecData.nozzle8_value_Lists.toList().toMutableList()))
                    put("nozzle9_value_Lists", JSONArray(currentSpecData.nozzle9_value_Lists.toList().toMutableList()))
//                    put("nozzle10_value_Lists", JSONArray(currentSpecData.nozzle10_value_Lists.toList().toMutableList()))
//                    put("nozzle11_value_Lists", JSONArray(currentSpecData.nozzle11_value_Lists.toList().toMutableList()))
                    put("box_need_avoid_Lists", JSONArray(currentSpecData.box_need_avoid_Lists.toList().toMutableList()))
                    put("box_release_type_Lists", JSONArray(currentSpecData.box_release_type_Lists.toList().toMutableList()))
                    put("box_name_List_Lists", JSONArray(currentSpecData.box_name_List_Lists.toList().toMutableList()))
                    put("box_value_List_Lists", JSONArray(currentSpecData.box_value_List_Lists.toList().toMutableList()))
                }

                //跳转到时序图页面，带上菜名和当前规格数据
                val intent = Intent(this@DishesCreateActivity, DishesTimePageActivity::class.java)
                intent.putExtra("name", viewModel.name.get().toString())
                intent.putExtra("spec", viewModel.numberList.get()!![currentSelectedIndex])
                intent.putExtra("specDataJson", specDataJson.toString())
                startActivity(intent)
            }
        }

        //添加加热设置按钮
        binding.dishesCreateDetailHeat.setOnClickListener {
            //判断当前是否可以添加步骤
            if ( !viewModel.judgeAddItem("加热设置") ){
                return@setOnClickListener
            }

            viewModel.addItem("加热设置","")
            // 确保 RecyclerView 的数据源已更新
            dishesCreateAdapter!!.notifyDataSetChanged()
            // 滚动到最新添加的项
            val newPosition = (viewModel.steep_index_List.get()?.size ?: 1) - 1
            binding.dishesCreateRecyclerview.post {
                binding.dishesCreateRecyclerview.smoothScrollToPosition(newPosition)
            }
        }

        //添加调味料按钮
        binding.dishesCreateDetailSauce.setOnClickListener {
            //判断当前是否可以添加步骤
            if ( !viewModel.judgeAddItem("调味料") ){
                return@setOnClickListener
            }

            viewModel.addItem("调味料","")
            // 确保 RecyclerView 的数据源已更新
            dishesCreateAdapter!!.notifyDataSetChanged()
            // 滚动到最新添加的项
            val newPosition = (viewModel.steep_index_List.get()?.size ?: 1) - 1
            binding.dishesCreateRecyclerview.post {
                binding.dishesCreateRecyclerview.smoothScrollToPosition(newPosition)
            }
        }

        //添加固体料盒按钮
        binding.dishesCreateDetailCassette.setOnClickListener {
            //判断当前是否可以添加步骤
            if ( !viewModel.judgeAddItem("固体料盒") ){
                return@setOnClickListener
            }

            viewModel.addItem("固体料盒","")
            // 确保 RecyclerView 的数据源已更新
            dishesCreateAdapter!!.notifyDataSetChanged()
            // 滚动到最新添加的项
            val newPosition = (viewModel.steep_index_List.get()?.size ?: 1) - 1
            binding.dishesCreateRecyclerview.post {
                binding.dishesCreateRecyclerview.smoothScrollToPosition(newPosition)
            }
        }

        //插入步骤按钮
        binding.dishesCreateDetailAdd.setOnClickListener {
            //判断当前是否可以添加步骤
            if ( !viewModel.judgeAddItem("插入步骤") ){
                return@setOnClickListener
            }
            //弹出步骤选择弹窗
            if ( viewModel.steep_type_List.get()!!.size > 0 ){
                if ( addStepDialog == null || !addStepDialog!!.isShowing ){
                    addStepDialog = AddStepDialog(this@DishesCreateActivity, R.style.Common_Dialog, viewModel.steep_type_List.get()!!)
                    addStepDialog!!.setAddStepDialogListener (object : AddStepDialog.AddStepDialogListener{
                        override fun confirm(type: String?, position: Int) {
                            viewModel.addItem(type!!,position.toString())
                            // 确保 RecyclerView 的数据源已更新
                            dishesCreateAdapter!!.notifyDataSetChanged()
                            // 滚动到插入的项
                            binding.dishesCreateRecyclerview.post {
                                binding.dishesCreateRecyclerview.smoothScrollToPosition(position)
                            }
                        }
                    })
                    addStepDialog!!.show()
                }
            } else {
                //Toast.makeText(this@DishesCreateActivity, "请先添加其他步骤",Toast.LENGTH_SHORT).show()
                ToastUtils.show(this@DishesCreateActivity, "请先添加其他步骤")
            }
        }

        //为了防止adapter嵌套时导致数据刷新异常，这里添加主动刷新监听操作
        binding.dishesCreateRecyclerview.layoutManager = LinearLayoutManager(this)
        binding.dishesCreateRecyclerview.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    val layoutManager = recyclerView.layoutManager as? LinearLayoutManager
                    val first = layoutManager!!.findFirstVisibleItemPosition()
                    val last = layoutManager.findLastVisibleItemPosition()

                    if ( first != last  ){
                        if ( moveY > 0 ){
                            recyclerView.adapter?.notifyItemRangeChanged(last - (last - first) + 1, last - first)
                        } else {
                            recyclerView.adapter?.notifyItemRangeChanged(first, last - first)
                        }
                    }
                    if (  lastLastItem != last || lastFirstItem != first ){
                        if ( moveY > 0 ){
                            recyclerView.adapter?.notifyItemRangeChanged(last, 1)
                        } else {
                            recyclerView.adapter?.notifyItemRangeChanged(first, 1)
                        }
                    }
                    lastFirstItem = first
                    lastLastItem = last
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                moveY = dy
            }
        })

        //adapter交互
        dishesCreateAdapter!!.setDishesCreateListener(object : DishesCreateAdapter.DishesCreateListener{
            override fun onDelete(position: Int) {
                //点击删除按钮，删除该项
                viewModel.deleteItem(position)
            }

            override fun setTime(position: Int, value: String) {
                //设置该项持续时间
                if ( value.isNotEmpty() ){
                    viewModel.time_long_List.get()?.set(position, value)
                    viewModel.time_value_List.get()?.set(position, TimeUtil.formatDuration(value.toInt(), "mm:ss"))
                }
            }

            override fun setHeat(position: Int, value: String) {
                //设置加热设置-火力
                viewModel.fire_value_List.get()?.set(position, value)
            }

            override fun setSpeed(position: Int, value: String) {
                //设置加热设置-转速
                viewModel.gripper_speed_value_List.get()?.set(position, value)
            }

            override fun setForward(position: Int, value: String) {
                //设置加热设置-转向
                viewModel.gripper_rotation_value_List.get()?.set(position, value)
            }

            override fun setUp(position: Int, value: String) {
                //设置加热设置-搅拌子状态
                viewModel.gripper_position_value_List.get()?.set(position, value)
            }

            override fun setNozzleNameList(position: Int, value: MutableList<String>) {
                //先处理删除逻辑
                for ( i in 0 until oldSauceList.size ){
                    if ( !viewModel.nozzle_name_List_List.get()?.get(position)!!.contains(oldSauceList[i]) ){
                        when ( oldSauceList[i] ){
                            "生抽" ->{
                                viewModel.nozzle1_value_List.get()?.set(position, "0")
                            }
                            "老抽" ->{
                                viewModel.nozzle2_value_List.get()?.set(position, "0")
                            }
                            "蚝油" ->{
                                viewModel.nozzle3_value_List.get()?.set(position, "0")
                            }
                            "动物油" ->{
                                viewModel.nozzle4_value_List.get()?.set(position, "0")
                            }
                            "植物油" ->{
                                viewModel.nozzle5_value_List.get()?.set(position, "0")
                            }
                            "盐水" ->{
                                viewModel.nozzle6_value_List.get()?.set(position, "0")
                            }
                            "醋" ->{
                                viewModel.nozzle7_value_List.get()?.set(position, "0")
                            }
                            "淀粉水" ->{
                                viewModel.nozzle8_value_List.get()?.set(position, "0")
                            }
                            "烹饪水" ->{
                                viewModel.nozzle9_value_List.get()?.set(position, "0")
                            }
//                            "烹饪水" ->{
//                                viewModel.nozzle10_value_List.get()?.set(position, "0")
//                            }
//                            "洗锅水" ->{
//                                viewModel.nozzle11_value_List.get()?.set(position, "0")
//                            }
                        }
                    }
                }
                // 获取当前的nozzle_name_List_List
                val nozzleNameListList = viewModel.nozzle_name_List_List.get() ?: mutableListOf()
                // 确保位置有效
                if (position >= 0 && position < nozzleNameListList.size) {
                    // 替换指定位置的列表
                    nozzleNameListList[position] = value
                } else if (position >= nozzleNameListList.size) {
                    // 如果位置超出当前列表范围，可以扩展列表
                    while (nozzleNameListList.size <= position) {
                        nozzleNameListList.add(mutableListOf())
                    }
                    nozzleNameListList[position] = value
                }
                // 更新到viewModel
                viewModel.nozzle_name_List_List.set(nozzleNameListList)
                //设置一个老列表,用于处理删除逻辑
                oldSauceList = viewModel.nozzle_name_List_List.get()!![position].toMutableList()
            }

            override fun setNozzleValueList(position: Int, value: MutableList<String>) {
                // 获取当前的nozzle_name_List_List
                val nozzleValueListList = viewModel.nozzle_value_List_List.get() ?: mutableListOf()

                // 确保位置有效
                if (position >= 0 && position < nozzleValueListList.size) {
                    // 替换指定位置的列表
                    nozzleValueListList[position] = value
                } else if (position >= nozzleValueListList.size) {
                    // 如果位置超出当前列表范围，可以扩展列表
                    while (nozzleValueListList.size <= position) {
                        nozzleValueListList.add(mutableListOf())
                    }
                    nozzleValueListList[position] = value
                }

                // 更新到viewModel
                viewModel.nozzle_value_List_List.set(nozzleValueListList)
                //设置调味料-调味料数据
                if (viewModel.nozzle_name_List_List.get()?.get(position)?.isNotEmpty() == true && viewModel.nozzle_value_List_List.get()?.get(position)?.isNotEmpty() == true ){//保证名称和数量列表长度相同
                    for ( i in 0 until viewModel.nozzle_name_List_List.get()?.get(position)!!.size){
                        when ( viewModel.nozzle_name_List_List.get()?.get(position)!![i] ){
                            "生抽" ->{
                                viewModel.nozzle1_value_List.get()?.set(position, viewModel.nozzle_value_List_List.get()?.get(position)!![i])
                            }
                            "老抽" ->{
                                viewModel.nozzle2_value_List.get()?.set(position, viewModel.nozzle_value_List_List.get()?.get(position)!![i])
                            }
                            "蚝油" ->{
                                viewModel.nozzle3_value_List.get()?.set(position, viewModel.nozzle_value_List_List.get()?.get(position)!![i])
                            }
                            "动物油" ->{
                                viewModel.nozzle4_value_List.get()?.set(position, viewModel.nozzle_value_List_List.get()?.get(position)!![i])
                            }
                            "植物油" ->{
                                viewModel.nozzle5_value_List.get()?.set(position, viewModel.nozzle_value_List_List.get()?.get(position)!![i])
                            }
                            "盐水" ->{
                                viewModel.nozzle6_value_List.get()?.set(position, viewModel.nozzle_value_List_List.get()?.get(position)!![i])
                            }
                            "醋" ->{
                                viewModel.nozzle7_value_List.get()?.set(position, viewModel.nozzle_value_List_List.get()?.get(position)!![i])
                            }
                            "淀粉水" ->{
                                viewModel.nozzle8_value_List.get()?.set(position, viewModel.nozzle_value_List_List.get()?.get(position)!![i])
                            }
                            "烹饪水" ->{
                                viewModel.nozzle9_value_List.get()?.set(position, viewModel.nozzle_value_List_List.get()?.get(position)!![i])
                            }
//                            "烹饪水" ->{
//                                viewModel.nozzle10_value_List.get()?.set(position, viewModel.nozzle_value_List_List.get()?.get(position)!![i])
//                            }
//                            "洗锅水" ->{
//                                viewModel.nozzle11_value_List.get()?.set(position, viewModel.nozzle_value_List_List.get()?.get(position)!![i])
//                            }
                        }
                    }
                }
            }

            override fun setCassetteNameList(position: Int, value: MutableList<String>) {
                //获取固体料盒-名称列表
                //先处理删除逻辑
//                if ( oldFoodList.size > viewModel.box_name_List_List.get()?.get(position)!!.size ){
//                    when ( oldFoodList.size ){
//                        1 ->{
//                            viewModel.box1_name_List.get()?.set(position, "")
//                            viewModel.box1_value_List.get()?.set(position, "")
//                        }
//                        2 ->{
//                            viewModel.box2_name_List.get()?.set(position, "")
//                            viewModel.box2_value_List.get()?.set(position, "")
//                        }
//                        3 ->{
//                            viewModel.box3_name_List.get()?.set(position, "")
//                            viewModel.box3_value_List.get()?.set(position, "")
//                        }
//                        4 ->{
//                            viewModel.box4_name_List.get()?.set(position, "")
//                            viewModel.box4_value_List.get()?.set(position, "")
//                        }
//                    }
//                }
                // 获取当前的box_name_List_List
                val boxNameListList = viewModel.box_name_List_List.get() ?: mutableListOf()

                // 确保位置有效
                if (position >= 0 && position < boxNameListList.size) {
                    // 替换指定位置的列表
                    boxNameListList[position] = value
                } else if (position >= boxNameListList.size) {
                    // 如果位置超出当前列表范围，可以扩展列表
                    while (boxNameListList.size <= position) {
                        boxNameListList.add(mutableListOf())
                    }
                    boxNameListList[position] = value
                }

                // 更新到viewModel
                viewModel.box_name_List_List.set(boxNameListList)
//                //设置一个老列表,用于处理删除逻辑
//                oldFoodList = viewModel.box_name_List_List.get()!![position].toMutableList()
            }

            override fun setCassetteValueList(position: Int, value: MutableList<String>) {
                //获取固体料盒-重量列表
                //设置食材参数
                // 获取当前的nozzle_name_List_List
                val boxValueListList = viewModel.box_value_List_List.get() ?: mutableListOf()

                // 确保位置有效
                if (position >= 0 && position < boxValueListList.size) {
                    // 替换指定位置的列表
                    boxValueListList[position] = value
                } else if (position >= boxValueListList.size) {
                    // 如果位置超出当前列表范围，可以扩展列表
                    while (boxValueListList.size <= position) {
                        boxValueListList.add(mutableListOf())
                    }
                    boxValueListList[position] = value
                }
                // 更新到viewModel
                viewModel.box_value_List_List.set(boxValueListList)

//                if (viewModel.box_name_List_List.get()?.get(position)?.isNotEmpty() == true && viewModel.box_value_List_List.get()?.get(position)?.isNotEmpty() == true){//保证名称和数量列表长度相同
//                    for ( i in 0 until viewModel.box_name_List_List.get()?.get(position)!!.size){
//                        when ( i ){
//                            0 ->{
//                                viewModel.box1_name_List.get()?.set(position, viewModel.box_name_List_List.get()?.get(position)!![i])
//                                viewModel.box1_value_List.get()?.set(position, viewModel.box_value_List_List.get()?.get(position)!![i])
//                            }
//                            1 ->{
//                                viewModel.box2_name_List.get()?.set(position, viewModel.box_name_List_List.get()?.get(position)!![i])
//                                viewModel.box2_value_List.get()?.set(position, viewModel.box_value_List_List.get()?.get(position)!![i])
//                            }
//                            2 ->{
//                                viewModel.box3_name_List.get()?.set(position, viewModel.box_name_List_List.get()?.get(position)!![i])
//                                viewModel.box3_value_List.get()?.set(position, viewModel.box_value_List_List.get()?.get(position)!![i])
//                            }
//                            3 ->{
//                                viewModel.box4_name_List.get()?.set(position, viewModel.box_name_List_List.get()?.get(position)!![i])
//                                viewModel.box4_value_List.get()?.set(position, viewModel.box_value_List_List.get()?.get(position)!![i])
//                            }
//                        }
//                    }
//                }
            }
            override fun setAddFood(position: Int, value: String) {
                //固体料盒-投菜方式
                when ( value ){
                    "常规投菜（投两下）" ->{
                        viewModel.box_release_type_List.get()?.set(position, "1")
                    }
                    "慢速投菜（滞留几秒后归位，不抖动）" ->{
                        viewModel.box_release_type_List.get()?.set(position, "2")
                    }
                    "快速投菜（投三下）" ->{
                        viewModel.box_release_type_List.get()?.set(position, "3")
                    }
                    "慢速投菜（投三下）" ->{
                        viewModel.box_release_type_List.get()?.set(position, "4")
                    }
                }
                var timeLimitSet = 0
                var foodLength = 0
                for ( i in 0 until viewModel.box_value_List_List.get()!!.size ){
                    if ( viewModel.box_value_List_List.get()!![i].isNotEmpty() ){
                        foodLength++
                    }
                }
                var releaseType = 1//默认为1
                if ( viewModel.box_release_type_List.get()!![position].isNotEmpty() ){
                    releaseType = viewModel.box_release_type_List.get()!![position].toInt()
                }
                val timeLimitItemSet = viewModel.applicationClass.Device_BoxThrow_2_Time(foodLength, releaseType)
                if ( timeLimitItemSet > timeLimitSet ){
                    timeLimitSet = timeLimitItemSet
                }
                if ( viewModel.time_long_List.get()!![position].isEmpty() ){
                    viewModel.time_long_List.get()!![position] = "0"
                }
                if ( viewModel.time_long_List.get()!![position].isNotEmpty() ){
                    viewModel.time_long_List.get()!![position] = timeLimitSet.toString()
                    viewModel.time_value_List.get()!![position] = TimeUtil.formatDuration(timeLimitSet.toString().toInt(), "mm:ss")
                }
                viewModel.updateDishesList()
                dishesCreateAdapter?.notifyItemRangeChanged(position, 1)
            }

            override fun setSwitchState(position: Int, value: String) {
                //固体料盒-避让方式
                viewModel.box_need_avoid_List.get()?.set(position, value)
            }
        })

        //保存按钮
        binding.dishesCreateSave.setOnClickListener {
            if ( viewModel.steep_type_List.get()!!.size <= 0 ){
                //Toast.makeText(this@DishesCreateActivity, "请先添加其他步骤",Toast.LENGTH_SHORT).show()
                ToastUtils.show(this@DishesCreateActivity, "请先添加其他步骤")
                return@setOnClickListener
            }
            //判断当前是否可以保存
            if ( !viewModel.judgeAddItem("保存") ){
                return@setOnClickListener
            }
            //保存当前规格的数据
            viewModel.saveCurrentSpecData(currentSelectedIndex)
            //判断是否所有规格都有至少一个步骤
            if ( !viewModel.judgeSaveAble() ){
                return@setOnClickListener
            }
            //弹出Loading弹窗
            LoadingDialogUtil.showLoadingDialog(this@DishesCreateActivity)
            viewModel.saveSpecsData("保存")
        }

        //保存并炒制按钮
        binding.dishesCreateSaveAndCook.setOnClickListener{
            if ( viewModel.steep_type_List.get()!!.size <= 0 ){
                //Toast.makeText(this@DishesCreateActivity, "请先添加其他步骤",Toast.LENGTH_SHORT).show()
                ToastUtils.show(this@DishesCreateActivity, "请先添加其他步骤")
                return@setOnClickListener
            }
            //判断当前是否可以保存
            if ( !viewModel.judgeAddItem("保存") ){
                return@setOnClickListener
            }
            //保存当前规格的数据
            viewModel.saveCurrentSpecData(currentSelectedIndex)
            //判断是否所有规格都有至少一个步骤
            if ( !viewModel.judgeSaveAble() ){
                return@setOnClickListener
            }
            //弹出Loading弹窗
            LoadingDialogUtil.showLoadingDialog(this@DishesCreateActivity)
            viewModel.saveSpecsData("保存并炒制")
        }
    }

    @SuppressLint("SetTextI18n")
    //弹出规格选择弹窗
    private fun showSpecDialog(){
        if ( !viewModel.numberList.get().isNullOrEmpty() ){
            val listSize = viewModel.numberList.get()!!.size
            if ( listSize <= 1 ){
                //Toast.makeText(this@DishesCreateActivity, "您只填了一个规格,无法切换", Toast.LENGTH_SHORT).show()
                ToastUtils.show(this@DishesCreateActivity, "您只填了一个规格,无法切换")
                return
            }
            val builder: AlertDialog.Builder = AlertDialog.Builder(this@DishesCreateActivity)
            builder.setTitle("选择规格")

            val portions = arrayOfNulls<String>(listSize)
            for (i in 0 until listSize) {
                portions[i] = viewModel.numberList.get()!![i]
            }

            builder.setItems(portions) { _, which ->
                binding.dishesCreateDetailNum.text = viewModel.numberList.get()!![which]
                binding.dishesCreateDetailWeight.text = viewModel.weightList.get()!![which] + "g"
                currentSelectedIndex = which
                viewModel.loadDateForIndex(currentSelectedIndex)
            }

            builder.show()
        }
    }

    //观察者模式，观察dishesList变化，更新adapter数据
    private fun setupObservers() {
        viewModel.dishesCreateList
            .distinctUntilChanged() // 过滤相同数据
            .observe(this) { list ->
                list?.let {
                    dishesCreateAdapter?.updateData(it)
                }
            }
    }

    //返回http结果
    private fun setupHttpResultObservers(){
        //如果有的话关闭Loading弹窗
        LoadingDialogUtil.closeLoadingDialog()
        //监听保存并跳转CookingActivity
        viewModel.navigateToCooking.observe(this) { exists ->
            exists?.let {
                val intent = Intent(this@DishesCreateActivity, CookActivity::class.java)
                intent.putExtra("vegetableId", it.toString())
                intent.putExtra("sid", (currentSelectedIndex + 1).toString())
                intent.putExtra("quantity", viewModel.numberList.get()?.get(currentSelectedIndex)!!.replace("份", ""))
                startActivity(intent)
                finish()
            } ?: run {
                // 处理网络请求异常的情况
                //Toast.makeText(this, "网络请求失败，请重试", Toast.LENGTH_SHORT).show()
                ToastUtils.show(this, "网络请求失败，请重试")
            }
        }

        //保存成功后退出页面
        viewModel.navigateSave.observe(this) { exists ->
            exists?.let {
                finish()
            } ?: run {
                // 处理网络请求异常的情况
                //Toast.makeText(this, "网络请求失败，请重试", Toast.LENGTH_SHORT).show()
                ToastUtils.show(this, "网络请求失败，请重试")
            }
        }

        //显示菜谱图片
        viewModel.faceImageValue.observe(this){ exists ->
            exists?.let {
                if ( exists.isNotEmpty() ){
                    Picasso.get().load(viewModel.faceImageValue.value.toString()).into(binding.dishesCreateDetailImage)
                }
            } ?: run {
                // 处理网络请求异常的情况
                //Toast.makeText(this, "网络请求失败，请重试", Toast.LENGTH_SHORT).show()
                ToastUtils.show(this, "网络请求失败，请重试")
            }
        }

        //显示初始规格数据
        viewModel.numberValue.observe(this){ exists ->
            exists?.let {
                binding.dishesCreateDetailNum.text = it
                currentSelectedIndex = 0
            } ?: run {
                // 处理网络请求异常的情况
                //Toast.makeText(this, "网络请求失败，请重试", Toast.LENGTH_SHORT).show()
                ToastUtils.show(this, "网络请求失败，请重试")
            }
        }

        //显示初始重量数据
        viewModel.weightValue.observe(this){ exists ->
            exists?.let {
                binding.dishesCreateDetailWeight.text = it
                currentSelectedIndex = 0
            } ?: run {
                // 处理网络请求异常的情况
                //Toast.makeText(this, "网络请求失败，请重试", Toast.LENGTH_SHORT).show()
                ToastUtils.show(this, "网络请求失败，请重试")
            }
        }
    }
}